package cc.eddic.examinationsystem.web;

import cc.eddic.examinationsystem.core.BaseController;
import cc.eddic.examinationsystem.domain.Option;
import cc.eddic.examinationsystem.domain.Question;
import cc.eddic.examinationsystem.dto.DemoUploadModel;
import cc.eddic.examinationsystem.dto.OptionResponse;
import cc.eddic.examinationsystem.dto.QuestionResponse;
import cc.eddic.examinationsystem.dto.StudentModel;
import cc.eddic.examinationsystem.repository.QuestionTxtRepository;
import lombok.extern.slf4j.Slf4j;

import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.transaction.Transactional;
import java.io.IOException;
import java.nio.charset.MalformedInputException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Slf4j
@Controller
@RequestMapping("/questions")
public class QuestionTxtController extends BaseController {

    @ResponseBody
    @Transactional
    public String add(String folderName) {

        List<String> correctanwserlist;
        List<String> filelist = readList(folderName);//解析文件
        List<Question> questions=new ArrayList<>();
        for (int i = 0; i < filelist.size(); ) {
            if (Objects.equals(filelist.get(i), "")) {
                continue;
            }
            if (filelist.get(i) == null) {
                continue;
            }
            Question q = new Question();//读取题目
            if (Character.isDigit(filelist.get(i).charAt(0))) {
                q = new Question(filelist.get(i).substring(filelist.get(i).indexOf("、") + 1));//构建问题
                i++;
            }
            //不存在正确答案，即格式不符合要求
            if (filelist.get(i).charAt(0) != '正')
                return "upload-result-fail";
            if (filelist.get(i).charAt(0) == '正') {//读取正确答案
                correctanwserlist = Arrays.asList(filelist.get(i).substring(5).split(""));
                i++;
                for (int j = 0; j < 4; j++) {//读取4个选项
                    char choice = filelist.get(i).charAt(0);
                    if (choice != 'A' && choice != 'B' && choice != 'C' && choice != 'D') //选项不符合要求
                        return "upload-result-fail";
                    String answer = filelist.get(i).substring(2);
                    boolean isCorrect = correctanwserlist.stream().anyMatch(x -> x.toCharArray()[0] == choice);
                    Option option = new Option(choice, answer, isCorrect);
                    q.add(option);
                    i++;
                }
            }
            questions.add(q);
//            repository.save(q);//存入数据库
        }
        for (Question q:questions)
            repository.save(q);
        return "upload-result-success";
    }

    @GetMapping("/txt")
    public String getQuestions(Model model) {

        List<Question> questionList = repository.findAll(); // 获取题目列表
        model.addAttribute("questionList", questionList); // 传递题目列表
        return "question-add-txt"; // 返回题目列表模板页面
    }

    @PostMapping("/upload/save")
    public String upload(@ModelAttribute DemoUploadModel uploadModel, Model model) {
        //判断是否为txt文件
        if (!Objects.requireNonNull(uploadModel.getFile().getOriginalFilename()).endsWith(".txt"))
            return "upload-result-fail";
        if (log.isDebugEnabled()) {
            log.debug("description = {}", uploadModel.getDescription());
            log.debug("{} {}", uploadModel.getFile().getOriginalFilename(), uploadModel.getFile().getSize());
        }
        //解析文件路径
        val p = Paths.get(uploadPath, FORMATTER.format(LocalDateTime.now()) + "_" + uploadModel.getFile().getOriginalFilename());
        try {
            uploadModel.getFile().transferTo(p);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        //调用add方法，对数据库添加内容
//        add(String.valueOf(p));
        return add(String.valueOf(p));
    }

    @GetMapping("/upload")
    public String uploadtxt(Model model) {
        model.addAttribute("uploadModel", new DemoUploadModel());//建立上传按钮
        return "upload-txt";
    }

    private final QuestionTxtRepository repository;
    //    @Value("${eddic.exam.upload.path}")
    @Value("${java.io.tmpdir}")
    private String uploadPath;
    //文件上传时，文件名加上时间，精确到毫秒，对文件名的时间解析
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss_SSS");

    public QuestionTxtController(QuestionTxtRepository questionTXTRepository) {
        this.repository = questionTXTRepository;
    }

    /*
    读取文件内容
    */
    public Stream<String> read(String textFileName) {
        try {
            val p = Paths.get(textFileName);
            return Files.lines(p);
        } catch (IOException e) {
            if (log.isDebugEnabled()) log.debug("{}", textFileName);
            return null;
        }
    }

    public List<String> readList(String textFileName) {
        return read(textFileName).collect(Collectors.toList());
    }
}

